package log

import (
	"gitee.com/851537/gbase"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
)

type Config struct {

	//可相对路径或绝对路径，必须以/结尾
	path     string
	filename string
	level    hlog.Level

	logrusFormatter  *logrus.TextFormatter
	lumberjackLogger *lumberjack.Logger
}

func defaultConfig() *Config {
	filename := "runtime.log"
	return NewConfig(
		WithPath("./log/"),
		WithFilename(filename),

		//用于logrus
		WithLogrusFormatter(&logrus.TextFormatter{
			TimestampFormat:           "2006-01-02 15:04:05",
			ForceColors:               true,
			EnvironmentOverrideColors: true,
			FullTimestamp:             true,
		}),

		//提供压缩和删除
		WithLumberjackLogger(&lumberjack.Logger{
			Filename:   filename,
			MaxSize:    20,    // 一个文件最大可达20M。
			MaxBackups: 5,     // 最多同时保存 5 个文件。
			MaxAge:     20,    // 一个文件最多可以保存 10 天。
			Compress:   false, // 用 gzip 压缩。
		}),
	)
}

func WithPath(path string) gbase.Option[*Config] {
	return func(obj *Config) {
		obj.path = path
	}
}

func WithFilename(filename string) gbase.Option[*Config] {
	return func(obj *Config) {
		obj.filename = filename
	}
}

func WithLevel(level hlog.Level) gbase.Option[*Config] {
	return func(obj *Config) {
		obj.level = level
	}
}
func WithLogrusFormatter(logrusFormatter *logrus.TextFormatter) gbase.Option[*Config] {
	return func(obj *Config) {
		obj.logrusFormatter = logrusFormatter
	}
}

func WithLumberjackLogger(lumberjackLogger *lumberjack.Logger) gbase.Option[*Config] {
	return func(obj *Config) {
		obj.lumberjackLogger = lumberjackLogger
	}
}
func NewConfig(opts ...gbase.Option[*Config]) (obj *Config) {
	obj = defaultConfig()
	for _, v := range opts {
		v(obj)
	}
	return
}
